import request from '../utils/request';

export const fetchLogin = async (data: any) => {
  const res = await request.post('/users/checkLogin', data);
  return res;
};

export const fetchGet = async () => {
  const res = await request.get('/users/info');
  console.log(res);
  return res;
};

export const handleLogin = async (loginForm: { account: string; password: string }) => {
  try {
    const response = await fetchLogin(loginForm).then(response => {
      if (response.code === 0) { // 假设code为0表示登录成功
        // 登录成功处理
        console.log('登录成功:', response);
        localStorage.setItem('token', response.token);
      } else {
        // 登录失败处理 
        console.error('登录失败:', response.msg);
        alert('账号或密码错误');
      }
    });
  } catch (error: any) {
    // 网络或其他错误处理
    console.error('登录失败:', error.message);
    alert('登录失败，请检查网络或联系管理员');
  }

  setTimeout(() => {
    fetchGet().then(res => {

      console.log(res); // 打印整个用户信息对象
      if (res && res.accountInfo) {
        // 存储账号信息到localStorage
        localStorage.setItem('account', res.accountInfo.account);
        localStorage.setItem('userGroup', res.accountInfo.userGroup);
        localStorage.setItem('imgUrl', res.accountInfo.imgUrl);
        localStorage.setItem('ctime', res.accountInfo.ctime);
        localStorage.setItem('id', res.accountInfo.id);
        window.location.href = '/home';
      }
    }).catch(error => {
      console.error('获取用户信息失败:', error);
    });
  }, 100);
  
};